<?php
//设置时区
date_default_timezone_set("Asia/Shanghai");
function getDir($dir)
{
    $dirArray[] = NULL;
    if (false != ($handle = opendir($dir))) {
        $i = 0;
        while (false !== ($file = readdir($handle))) {
            //去掉"“.”、“..”以及带“.xxx”后缀的文件
            if ($file != "." && $file != ".." && !strpos($file, ".")) {
                $dirArray[$i] = $file;
                $i++;
            }
        }
        closedir($handle);
    }
    return $dirArray;
}

function getFile($dir)
{
    $fileArray[] = NULL;
    if (false != ($handle = opendir($dir))) {
        $i = 0;
        while (false !== ($file = readdir($handle))) {
            //去掉"“.”、“..”以及带“.xxx”后缀的文件
            if ($file != "." && $file != ".." && strpos($file, ".")) {
                $fileArray[$i] = $file;
                if ($i == 100) {
                    break;
                }
                $i++;
            }
        }
        closedir($handle);
    }
    return $fileArray;
}

function Random_String($length)
{
    $str = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));
    shuffle($str);
    $str = implode('', array_slice($str, 0, $length));
    return $str;
}

//登录状态检查
function Login_Status(){
    if ($_SESSION['login_status']==1){
        return true;
    }else{
        return false;
    }
}
//获取系统负载
class SystemInfoWindows
{
    /**
     * 判断指定路径下指定文件是否存在，如不存在则创建
     * @param string $fileName 文件名
     * @param string $content 文件内容
     * @return string 返回文件路径
     */
    private function getFilePath($fileName, $content)
    {
        $path = dirname(__FILE__) . "\\$fileName";
        if (!file_exists($path)) {
            file_put_contents($path, $content);
        }
        return $path;
    }
    /**
     * 获得cpu使用率vbs文件生成函数
     * @return string 返回vbs文件路径
     */
    private function getCupUsageVbsPath()
    {
        return $this->getFilePath(
            'cpu_usage.vbs',
            "On Error Resume Next
    Set objProc = GetObject(\"winmgmts:\\\\.\\root\cimv2:win32_processor='cpu0'\")
    WScript.Echo(objProc.LoadPercentage)"
        );
    }
    /**
     * 获得总内存及可用物理内存JSON vbs文件生成函数
     * @return string 返回vbs文件路径
     */
    private function getMemoryUsageVbsPath()
    {
        return $this->getFilePath(
            'memory_usage.vbs',
            "On Error Resume Next
    Set objWMI = GetObject(\"winmgmts:\\\\.\\root\cimv2\")
    Set colOS = objWMI.InstancesOf(\"Win32_OperatingSystem\")
    For Each objOS in colOS
     Wscript.Echo(\"{\"\"TotalVisibleMemorySize\"\":\" & objOS.TotalVisibleMemorySize & \",\"\"FreePhysicalMemory\"\":\" & objOS.FreePhysicalMemory & \"}\")
    Next"
        );
    }
    /**
     * 获得CPU使用率
     * @return Number
     */
    public function getCpuUsage()
    {
        $path = $this->getCupUsageVbsPath();
        exec("cscript -nologo $path", $usage);
        return $usage[0];
    }
    /**
     * 获得内存使用率数组
     * @return array
     */
    public function getMemoryUsage()
    {
        $path = $this->getMemoryUsageVbsPath();
        exec("cscript -nologo $path", $usage);
        $memory = json_decode($usage[0], true);
        $memory['usage'] = Round((($memory['TotalVisibleMemorySize'] - $memory['FreePhysicalMemory']) / $memory['TotalVisibleMemorySize']) * 100);
        return $memory;
    }
}

//Redis
function Redis_Link()
{
    global $redis_address;
    global $redis_port;
    global $redis_auth;
    $redis = new Redis();
    $redis->pconnect($redis_address, $redis_port);
    $redis->auth($redis_auth);
    $redis->select(1);
    return $redis;
}
//删除目录及文件
function Del_Dir( $dirName )
{
    if ( $handle = opendir( "$dirName" ) ) {
        while ( false !== ( $item = readdir( $handle ) ) ) {
            if ( $item != "." && $item != ".." ) {
                if ( is_dir( "$dirName/$item" ) ) {
                    Del_Dir( "$dirName/$item" );
                }
            }
        }
        closedir( $handle );
    }
}
//更改系统设置
function Change_Config($name,$value){
    $db_link=DB_Link();
    $redis=Redis_Link();
    $row_config=mysqli_fetch_array(mysqli_query($db_link,"SELECT * FROM `setting` WHERE `name` = '".$name."'"));
    if (empty($row_config['ID'])){
        return false;
    }else{
        mysqli_query($db_link,"UPDATE `setting` SET `data` = '".$value."' WHERE `name` = '".$name."'");
        $redis->del('Config_'.$name);
        return true;
    }
}

//Mysql
function DB_Link()
{
    global $mysql_address;
    global $mysql_port;
    global $mysql_username;
    global $mysql_password;
    global $mysql_db_name;
    $db_link = mysqli_connect($mysql_address, $mysql_username, $mysql_password, $mysql_db_name, $mysql_port);
    if (!$db_link) {
        echo "Mysql Error";
        exit;
    } else {
        mysqli_query($db_link, "SET NAMES utf8");
        return $db_link;
    }
}

//Get Config
//Get Config
function Get_Config($name)
{
    $redis = Redis_Link();
    $result = $redis->get('Config_' . $name);
    if (empty($result)) {
        $db_link = DB_Link();
        $row_config = mysqli_fetch_array(mysqli_query($db_link, "SELECT * FROM setting WHERE name = '" . $name . "'"));
        if (empty($row_config)) {
            return 0;
        } else {
            $redis->set('Config_' . $name, $row_config['data']);
            return $row_config['data'];
        }
    } else {
        return $result;
    }
}

//Output API
function Col_echo($text, $color)
{
    switch ($color) {
        case "black":
            $prefix = "\033[0;30m";
            break;
        case "dark_gray":
            $prefix = "\033[1;30m";
            break;
        case "blue":
            $prefix="\033[0;34m";
            break;
        case "light_blue":
            $prefix="\033[1;34m";
            break;
        case "green":
            $prefix="\033[0;32m";
            break;
        case "light_green":
            $prefix="\033[1;32m";
            break;
        case "cyan":
            $prefix="\033[0;36m";
            break;
        case "light_cyan":
            $prefix="\033[1;36m";
            break;
        case "red":
            $prefix="\033[0;31m";
            break;
        case "light_red":
            $prefix="\033[1;31m";
            break;
        case "purple":
            $prefix="\033[0;35m";
            break;
        case "light_purple":
            $prefix="\033[1;35m";
            break;
        case "brown":
            $prefix="\033[0;33m";
            break;
        case "yellow":
            $prefix="\033[1;33m";
            break;
        case "light_gray":
            $prefix="\033[0;37m";
            break;
        case "white":
            $prefix="\033[1;37m";
            break;
        default:
            $prefix="\033[0m";
            break;
    }
    echo $prefix.$text."\033[0m";
}

function encrypt($string,$operation,$key=''){
    $key=md5($key);
    $key_length=strlen($key);
    $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string;
    $string_length=strlen($string);
    $rndkey=$box=array();
    $result='';
    for($i=0;$i<=255;$i++){
        $rndkey[$i]=ord($key[$i%$key_length]);
        $box[$i]=$i;
    }
    for($j=$i=0;$i<256;$i++){
        $j=($j+$box[$i]+$rndkey[$i])%256;
        $tmp=$box[$i];
        $box[$i]=$box[$j];
        $box[$j]=$tmp;
    }
    for($a=$j=$i=0;$i<$string_length;$i++){
        $a=($a+1)%256;
        $j=($j+$box[$a])%256;
        $tmp=$box[$a];
        $box[$a]=$box[$j];
        $box[$j]=$tmp;
        $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));
    }
    if($operation=='D'){
        if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)){
            return substr($result,8);
        }else{
            return'';
        }
    }else{
        return str_replace('=','',base64_encode($result));
    }
}

//get media file infomation
define('FFMPEG_CMD', 'ffmpeg -i "%s" 2>&1');
function getVideoInfo($file){
    ob_start();
    passthru(sprintf(FFMPEG_CMD, $file));
    $video_info = ob_get_contents();
    ob_end_clean();

    // 使用输出缓冲，获取ffmpeg所有输出内容
    $ret = array();

    // Duration: 00:33:42.64, start: 0.000000, bitrate: 152 kb/s
    if (preg_match("/Duration: (.*?), start: (.*?), bitrate: (\d*) kb\/s/", $video_info, $matches)){
        $ret['duration'] = $matches[1]; // 视频长度
        $duration = explode(':', $matches[1]);
        $ret['seconds'] = $duration[0]*3600 + $duration[1]*60 + $duration[2]; // 转为秒数
        $ret['start'] = $matches[2]; // 开始时间
        $ret['bitrate'] = $matches[3]; // bitrate 码率 单位kb
    }

    // Stream #0:1: Video: rv20 (RV20 / 0x30325652), yuv420p, 352x288, 117 kb/s, 15 fps, 15 tbr, 1k tbn, 1k tbc
    if(preg_match("/Video: (.*?), (.*?), (.*?)[,\s]/", $video_info, $matches)){
        $ret['vcodec'] = $matches[1];     // 编码格式
        $ret['vformat'] = $matches[2];    // 视频格式
        $ret['resolution'] = $matches[3]; // 分辨率
        list($width, $height) = explode('x', $matches[3]);
        $ret['width'] = $width;
        $ret['height'] = $height;
    }

    // Stream #0:0: Audio: cook (cook / 0x6B6F6F63), 22050 Hz, stereo, fltp, 32 kb/s
    if(preg_match("/Audio: (.*), (\d*) Hz/", $video_info, $matches)){
        $ret['acodec'] = $matches[1];      // 音频编码
        $ret['asamplerate'] = $matches[2]; // 音频采样频率
    }

    if(isset($ret['seconds']) && isset($ret['start'])){
        $ret['play_time'] = $ret['seconds'] + $ret['start']; // 实际播放时间
    }

    $ret['size'] = filesize($file); // 视频文件大小
    if (!isset($ret['bitrate'])){
        return "bad";
    }
    $video_info = iconv('gbk','utf8', $video_info);
    return array($ret, $video_info);

}


//log function
function exec_log($str)
{
    global $DEBUG;
    if ($DEBUG == 'yes') {
        $t = date("Y-m-d H:i:s");
        $s = $t . ":" . $str . "\r\n";
        $file = "log/" . date("YmdH") . ".log";
        $fp = fopen($file, "a");
        fwrite($fp, $s);
        fclose($fp);
    }

    exec($str);
}

//log function
function w_log($str)
{
    global $DEBUG;
    if ($DEBUG == 'yes') {
        $t = date("Y-m-d H:i:s");
        $s = $t . ":" . $str . "\r\n";
        $file = "log/" . date("YmdH") . ".log";
        $fp = fopen($file, "a");
        fwrite($fp, $s);
        fclose($fp);
    }

}
